﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.ComponentModel;

namespace CRPTModularCorrousel
{
    [ParseChildren(true, "Items"), PersistChildren(true)]
    public class ModularControl : Control
    {
        private const string MODULAR_ID = "moodular";

        [Browsable(true)]
        [Category("Behavior")]
        public bool IsRepeat { set; get; }

        public ModularControl()
        {
            Items = new ItemTemplate();
            Repeat = new ItemRepeaterTemplate();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            var bulletList = new HtmlGenericControl("ul");
            if (!IsRepeat)
            {
                LoadItems(bulletList);
            }
            else
            {
                LoadRepeater(bulletList);
            }
            bulletList.Attributes.Add("id", MODULAR_ID);
            this.Controls.Add(bulletList);
            //Page.Header.Controls.Add(new LiteralControl("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + ResolveUrl("~/Styles/moodular.css") + "\" />"));
        }

        private void LoadItems(Control bulletList)
        {
            foreach (var item in Items)
            {
                item.InstantiateIn(bulletList);
            }
        }

        private void LoadRepeater(Control bulletList)
        {
            ModularRepeaterTemplate firstArgument = Repeat.First();
            ModularRepeaterTemplate repeater;
            for (int count = 1; count <= firstArgument.RepeaterCount; count++)
            {
                repeater = new ModularRepeaterTemplate(firstArgument);
                repeater.CurrentIndex = count;
                repeater.InstantiateIn(bulletList);
            }
        }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ItemTemplate Items { get; set; }


        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ItemRepeaterTemplate Repeat { get; set; }

    }
}
